package com.jp.knowledge.my.activity;

import android.content.Intent;
import android.os.Handler;
import android.support.v4.content.LocalBroadcastManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.comm.SlidingActivity;
import com.jp.knowledge.broad.LocalBroadCast;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.logic.PersonLogic;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.my.model.OrganizaModel;
import com.jp.knowledge.my.resources.OrganizeJoinRes;
import com.jp.knowledge.my.util.MyUtil;
import com.jp.knowledge.util.ResultSubscriber;

import org.xutils.view.annotation.ViewInject;

import java.util.List;

public class PositionActivity extends SlidingActivity implements View.OnClickListener{

    @ViewInject(R.id.position_edit_tv)
    protected EditText editText;

    @Override
    protected int getResourceId() {
        return R.layout.activity_position;
    }

    @Override
    protected void init() {
        initTitle(getString(R.string.join_position_edit));
        editText.setText(getIntent().getStringExtra(OrganizeJoinRes.POSITION));
        rightBtn.setOnClickListener(this);
        leftIcon.setOnClickListener(this);
        editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE && editText.getText().toString().trim().length() > 0) {
                    MyUtil.closeKeyword(PositionActivity.this, editText);
                    editFinishBnClick();
                }
                return true;
            }
        });
    }

    protected void initTitle(String title) {
        topName.setText(title);
        topDesc.setVisibility(View.GONE);
        leftIcon.setImageResource(R.mipmap.arrow_white_left);
        rightIcon.setVisibility(View.GONE);
        rightBtn.setVisibility(View.VISIBLE);
        rightBtn.setText(R.string.sure);
    }

    @Override
    protected void onStart() {
        super.onStart();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                MyUtil.startKeyword(PositionActivity.this, editText);
            }
        }, 300);
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.icon_left) {
            finishSelf();
        } else if(v.getId() == R.id.right_bn) {
            editFinishBnClick();
        }
    }

    protected void finishSelf(){
        MyUtil.closeKeyword(PositionActivity.this, editText);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                finish();
            }
        }, 300);
    }

    protected void editFinishBnClick(){
//        Intent intent = getIntent();
//        intent.putExtra(OrganizeJoinRes.RESPONSE_RESULT, editText.getText().toString());
//        setResult(RESULT_OK, intent);
//        finishSelf();
        joinToOrganization();
    }

    private void joinToOrganization(){
        loading.show();
        Intent intent = getIntent();
        JsonObject param = new JsonObject();
        int type = intent.getIntExtra(OrganizeJoinRes.REQUEST_CODE, 0);
        param.addProperty("token", HttpHelper.token);
        param.addProperty("id", intent.getStringExtra(OrganizeJoinRes.ID));
        param.addProperty("type", type+1);
        param.addProperty("depaId", intent.getStringExtra(OrganizeJoinRes.DEPA_ID));
        String position = editText.getText().toString();
        if(position != null && position.length() > 0)
            param.addProperty("position", position);
        HttpHelper.getInstance(this).commitJoinOrganize(param, type, new ResultSubscriber.OnResultListener(){
            @Override
            public void onStart(int requestType) {}
            @Override
            public void onCompleted(int requestType) {
                loading.cancel();
            }
            @Override
            public void onError(int requestType) {
                loading.cancel();
            }
            @Override
            public void onNext(IModel data, int requestType) {
                if(data.getErrcode() != 0){
                    ToasUtil.toast(PositionActivity.this, data.getMessage());
                    onError(requestType);
                    return;
                }
                List<OrganizaModel> organizaModels = data.getList(OrganizaModel.class);
                if(organizaModels != null && organizaModels.size() > 0) {
                    List<OrganizaModel> userOrganizes = application.getUserData().getCompanyList();
                    application.getUserData().setCompanyList(organizaModels);
                    for(OrganizaModel organizaModel : organizaModels){
                        if(!userOrganizes.contains(organizaModel)){
                            LocalBroadcastManager.getInstance(mContext)
                                    .sendBroadcast(new Intent(LocalBroadCast.COMPANY_JOIN)
                                            .putExtra("joinCompany", organizaModel)
                                            .putExtra("index", organizaModels.indexOf(organizaModel)));
                            break;
                        }
                    }
                }
//                OrganizaModel organizaModel = new OrganizaModel();
//                organizaModel.setCompanyType(getIntent().getIntExtra(OrganizeJoinRes.REQUEST_CODE, 0)+1);
//                organizaModel.setCompanyId(getIntent().getStringExtra(OrganizeJoinRes.ID));
//                organizaModel.setCompanyName(getIntent().getStringExtra(OrganizeJoinRes.COMPANY_NAME));
//                LocalBroadcastManager.getInstance(context)
//                        .sendBroadcast(new Intent(LocalBroadCast.COMPANY_JOIN)
//                                .putExtra("joinCompany", organizaModel));
//                updataUserData();
                ToasUtil.toast(PositionActivity.this, "组织加入成功");
                startActivity(new Intent(PositionActivity.this, OrganizeActivity.class));
                PositionActivity.this.finishSelf();
            }
        });
    }

    private void updataUserData(){
        if(application.getUserData() == null
                || application.getUserData().getCompanyId() == null
                || application.getUserData().getCompanyId().trim().length() == 0){
            new PersonLogic(this).getUserData();
        }
    }
}
